package com.ls.demo.annotation;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * @program: simpleframework
 * @description:
 * @author: lishuang
 * @create: 2021-11-22 16:35
 **/

public class AnnotationParser {
    //解析类的注解
    public static void parseTypeAnnotation() throws Exception {
        Class<?> clazz = Class.forName("com.ls.demo.annotation.StudyCourse");
        Annotation[] annotations = clazz.getAnnotations();
        for (Annotation annotation : annotations) {
            CourseInfoAnnotation courseInfoAnnotation = (CourseInfoAnnotation) annotation;
            System.out.println(annotation);
            System.out.println("课程名：" + courseInfoAnnotation.courseName());
        }
    }

    public static void parseField() throws Exception {
        Class<?> clazz = Class.forName("com.ls.demo.annotation.StudyCourse");
        Field[] fields = clazz.getDeclaredFields();
        for (Field f : fields) {
            //判断成员变量中是否有指定注解类型的注解
            boolean hasAnnotation = f.isAnnotationPresent(PersonInfoAnnotation.class);
            if (hasAnnotation) {
                PersonInfoAnnotation personInfoAnnotation = f.getAnnotation(PersonInfoAnnotation.class);
                System.out.println("名字：" + personInfoAnnotation.name() + "\n" +
                        "年龄：" + personInfoAnnotation.age() + "\n" +
                        "性别：" + personInfoAnnotation.gender());
                for (String language : personInfoAnnotation.language()) {
                    System.out.println("开发语言：" + language);
                }

            }
        }
    }

    /**
     * 解析方法
     * @throws ClassNotFoundException
     */
    public static void parseMethodAnnotation() throws ClassNotFoundException {
        Class clazz = Class.forName("com.ls.demo.annotation.StudyCourse");
        Method[] methods = clazz.getDeclaredMethods();
        for (Method method : methods) {
            /**
             * 判断方法中是否有指定注解类型的注解
             */
            boolean hasAnnotation = method.isAnnotationPresent(CourseInfoAnnotation.class);
            if (hasAnnotation) {
                CourseInfoAnnotation courseInfoAnnotation = method.getAnnotation(CourseInfoAnnotation.class);
                System.out.println("\n" + "课程名：" + courseInfoAnnotation.courseName() + "\n" +
                        "课程标签：" + courseInfoAnnotation.courseTag() + "\n" +
                        "课程简介：" + courseInfoAnnotation.des() + "\n" +
                        "课程序号：" + courseInfoAnnotation.courseIndex() + "\n");
            }
        }
    }

    public static void main(String[] args) throws Exception {
//        parseTypeAnnotation();
        parseField();
//        System.setProperty("sun.misc.ProxyGenerator.saveGeneratedFiles","true");
    }
}
